﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using IMS.Api.Repository;
using IMS.Api.Entity;
using Microsoft.Extensions.Configuration;
using IMS.Api.Utils;
using IMS.Api.ParamModel;
using Microsoft.AspNetCore.Authorization;

namespace IMS.Api.Controllers
{
    // 全局验证token
    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class AddressesController : ControllerBase
    {
        // 定义调用收货地址表的接口
        private IRepository<Addresses> _addressesRepository;
        // 定义调用文章表的接口
        private IRepository<Commodities> _commoditiesRepository;
        // 定义调用用户表的接口
        private IRepository<Users> _usersRepository;
        // 定义token
        private TokenParameter _tokenParameter;
        // 定义配置访问接口
        private readonly IConfiguration _configuration;

        // 依赖注入
        public AddressesController(IConfiguration configuration, IRepository<Addresses> addressessRepository, IRepository<Commodities> commoditiesRepository, IRepository<Users> usersRepository)
        {
            _configuration = configuration;
            _addressesRepository = addressessRepository;
            _commoditiesRepository = commoditiesRepository;
            _usersRepository = usersRepository;
            // Token
            _tokenParameter =
                configuration
                    .GetSection("tokenParameter")
                    .Get<TokenParameter>();
        }

        // 获取收货地址表数据
        [HttpGet]
        public dynamic GetAddressesList([FromQuery] Pager pager)
        {
            // 页码（当前第几页）
            var pageIndex = pager.PageIndex;
            // 页码（当前第几页）
            var pageSize = pager.PageSize;


            // 获取收货地址表数据
            var addresses = _addressesRepository.Table.ToList();
            // 判断收货地址表是否为空
            if (addresses != null)
            {
                // 收货地址表不为空
                // 判断是否进入回收站
                var recycle = pager.Recycle ? pager.Recycle : false;
                if (recycle)
                {
                    // 查看状态为删除收货地址表
                    var deletedAddresses = _addressesRepository.DeleteTable;
                    // 给状态为删除的收货地址表分页
                    var deletedTable = deletedAddresses.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                    return JsonHelper.Serialize(new
                    {
                        Data = new { DeletedAddresses = deletedTable, Pager = new { pageIndex, pageSize, PageTotal = deletedAddresses.Count() } },
                        Meta = new
                        {
                            Msg = "获取已删除收货地址列表成功！",
                            Status = 200
                        }
                    });
                }
                else
                {
                    // 给状态为存在的收货地址表分页
                    var Addresses = addresses.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

                    return JsonHelper.Serialize(new
                    {
                        Data = new { Addresses = Addresses, Pager = new { pageIndex, pageSize, PageTotal = Addresses.Count() } },
                        Meta = new
                        {
                            Msg = "获取收货地址列表成功！",
                            Status = 200
                        }
                    });
                }
            }
            else
            {
                // 收货地址表为空
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "收货地址列表获取异常！",
                        Status = 400
                    }
                });
            }
        }

        // 获取用户Id获取地址
        [HttpGet("uid/{id}"), Route("uid")]
        public dynamic GetAddressesByPid(int id)
        {
            // 判断传入的Id是否在收货地址表存在
            var addresses = _addressesRepository.Table.ToList().Where(x => x.FromUserId == id);
            if (addresses != null)
            {
                // 查询的Id的收货地址表存在
                return JsonHelper.Serialize(new
                {
                    Data = new { Addresses = addresses },
                    Meta = new
                    {
                        Msg = "收货地址数据获取成功！",
                        Status = 200
                    }
                });
            }
            else
            {
                // 查询的Id的收货地址表不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "收货地址数据获取异常！",
                        Status = 400
                    }
                });
            }
        }

        // 根据收货地址Id获取收货地址
        [HttpGet("id/{id}"), Route("id")]
        public dynamic GetAddressesById(int id)
        {
            // 判断传入的Id是否在收货地址表存在
            var addresses = _addressesRepository.GetById(id);
            if (addresses != null)
            {
                // 查询的Id的收货地址表存在
                return JsonHelper.Serialize(new
                {
                    Data = addresses,
                    Meta = new
                    {
                        Msg = "收货地址数据获取成功！",
                        Status = 200
                    }
                });
            }
            else
            {
                // 查询的Id的收货地址表不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "收货地址数据获取异常！",
                        Status = 400
                    }
                });
            }
        }

        // 添加新收货地址
        [HttpPost]
        public dynamic AddAddresses(NewAddress model)
        {
            // 收货人Id
            var fromUserId = model.FromUserId;
            // 收货人名称
            var consignee = model.Consignee;
            // 用户地址
            var userAddress = model.UserAddress;
            // 用户电话
            var telephoneNumber = model.TelephoneNumber;

            // 判断收货地址名称是否为空
            if (string.IsNullOrEmpty(model.UserAddress))
            {
                // 收货地址名称为空时
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "插入的收货地址名称不能为空，请确认后重试！",
                        Status = 400
                    }
                });
            }
            else
            {
                // 收货地址统计
                var Addresses = _addressesRepository.Table.Where(x => x.UserAddress == userAddress).Count();
                // 判断要创建的收货地址不存在
                if (Addresses == 0)
                {
                    // 创建新收货地址
                    var addresses = new Addresses
                    {
                        FromUserId = fromUserId,
                        Consignee = consignee,
                        UserAddress = userAddress,
                        TelephoneNumber = telephoneNumber
                    };
                    // 收货地址插入
                    _addressesRepository.Insert(addresses);
                    return JsonHelper.Serialize(new
                    {
                        Data = addresses,
                        Meta = new
                        {
                            Msg = "创建新收货地址成功！",
                            Status = 200
                        }
                    });
                }
                else
                {
                    // 收货地址已经存在了
                    return JsonHelper.Serialize(new
                    {
                        Data = "",
                        Meta = new
                        {
                            Msg = "该收货地址已存在，无法重复创建！",
                            Status = 400
                        }
                    });
                }
            }
        }

        // 收货地址信息修改
        [HttpPut("{id}")]
        public dynamic ModAddresses(int id, NewAddress model)
        {
            var addresses = _addressesRepository.GetById(id);
            // 判断所修改收货地址Id是否存在
            if (addresses != null)
            {
                // 收货人名称
                addresses.Consignee = model.Consignee;
                // 收货地址名称
                addresses.UserAddress = model.UserAddress;
                // 收货用户电话
                addresses.TelephoneNumber = model.TelephoneNumber;
                // 统计要修改的收货地址名称在收货地址表中的数量
                var addressessCount = _addressesRepository.Table.Where(x => x.UserAddress == model.UserAddress).ToList().Count();
                // 判断要修改的收货地址名称是否已经创建过了
                if (addressessCount == 0)
                {
                    // 要修改的名称未创建
                    // 收货地址更新
                    _addressesRepository.Update(addresses);
                    return JsonHelper.Serialize(new
                    {
                        Data = addresses,
                        Meta = new
                        {
                            Msg = string.Format("你修改的收货地址的id为: {0} ，已经修改成功，请注意查收！", id),
                            Status = 200
                        }
                    });
                }
                else
                {
                    // 要修改的名称已创建
                    return JsonHelper.Serialize(new
                    {
                        Data = "",
                        Meta = new
                        {
                            Msg = string.Format("你修改的收货地址的id为: {0} ，要修改的收货地址名称已存在，请尝试修改为其他名称！", id),
                            Status = 400
                        }
                    });
                }

            }
            else
            {
                // 该收货地址Id不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "指定Id的收货地址不存在，请确认后重试！",
                        Status = 400
                    }
                });
            }
        }

        // 收货地址状态可用信息修改
        [HttpPut("status/{id}"), Route("status")]
        public dynamic ModStatus(int id)
        {
            var addresses = _addressesRepository.GetById(id);
            // 判断对应Id的收货地址是否存在
            if (addresses != null)
            {
                // 指定Id的收货地址存在
                _addressesRepository.ActiveStatus(id);
                return JsonHelper.Serialize(new
                {
                    Data = addresses,
                    Meta = new
                    {
                        Msg = string.Format("你修改的状态对应收货地址的id为: {0} ，已经修改成功，请注意查收！", id),
                        Status = 200
                    }
                });
            }
            else
            {
                // 指定Id的收货地址不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "指定Id的收货地址不存在，请确认后重试！",
                        Status = 400
                    }
                });
            }
        }

        // 收货地址信息删除（伪删除）
        [HttpDelete("{id}")]
        public dynamic DeleteAddresses(int id)
        {
            var addresses = _addressesRepository.GetById(id);
            // 判断对应Id的收货地址是否存在
            if (addresses != null)
            {
                // 对应Id的收货地址存在
                // 伪删除操作
                _addressesRepository.PseudoDeletion(id);
                return JsonHelper.Serialize(new
                {
                    Data = addresses,
                    Meta = new
                    {
                        Msg = string.Format("你删除的收货地址Id为 {0} 的数据,伪删除成功！", id),
                        Status = 200
                    }
                });
            }
            else
            {
                // 对应Id的收货地址不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = string.Format("找不到的收货地址Id为 {0} 的数据,执行伪删除操作,", id),
                        Status = 400
                    }
                });
            }
        }

        // 收货地址信息删除（彻底删除）
        [HttpDelete("delete/{id}"), Route("delete")]
        public dynamic CompletelyDeleteAddresses(int id)
        {
            var addresses = _addressesRepository.GetById(id);
            // 判断对应Id的收货地址是否存在
            if (addresses != null)
            {   // 指定Id的收货地址存在
                // 彻底删除
                _addressesRepository.Delete(id);
                return JsonHelper.Serialize(new
                {
                    Data = addresses,
                    Meta = new
                    {
                        Msg = string.Format("你删除的Id为 {0} 的收货地址数据,彻底删除成功！", id),
                        Status = 200
                    }
                });
            }
            else
            {
                // 指定Id的收货地址不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = string.Format("找不到的Id为 {0} 的收货地址数据,无法执行彻底删除操作,", id),
                        Status = 400
                    }
                });
            }
        }

        // 恢复被删除的收货地址数据
        [HttpDelete("recovery/{id}"), Route("recovery")]
        public dynamic RecoveryAddresses(int id)
        {
            var addresses = _addressesRepository.GetById(id);
            // 判断对应Id的收货地址是否存在
            if (addresses != null)
            {
                // 指定Id的收货地址存在
                // 恢复数据
                _addressesRepository.Recovery(id);
                return JsonHelper.Serialize(new
                {
                    Data = addresses,
                    Meta = new
                    {
                        Msg = string.Format("你恢复的收货地址的id为: {0} ，已经恢复成功，请注意查收！", id),
                        Status = 200
                    }

                });
            }
            else
            {
                // 指定Id的收货地址不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "指定Id的收货地址不存在，恢复错误，请确认后重试！",
                        Status = 400
                    }
                });
            }
        }
    }
}
